#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <fcntl.h>
#include <getopt.h>

#include "mapmod.h"

enum Action { UNDEFINED, START, STOP, RPM } action = UNDEFINED;

#define	DEVICE	"/dev/memio0"

int main ( int argc, char* argv[] ) {
	int c;
	int digit_optind = 0;
	int dd = -1;
	int rpm = -1;
	action = STOP;
	while (1) {
		int this_option_optind = optind ? optind : 1;
		int option_index = 0;
        static struct option long_options[] = {
            { "start",  no_argument, 0, 's' },
            { "stop", no_argument, 0, 'f' },
            { "rpm", required_argument, 0, 'r' },
            { 0, 0, 0, 0 }
        };
        c = getopt_long( argc, argv, "sf", long_options, &option_index );
        if (c == -1)
        	break;
        switch (c) {
        case 's':
        	action = START;
        	printf("START\n");
        	break;
        case 'f':
        	action = STOP;
        	printf("STOP\n");
        	break;
        case 'r':
        	rpm = atoi( optarg );
        	switch (rpm) {
        	case 2:
        	case 4:
        	case 6:
        	case 12:
        		action = RPM;
        		printf("RPM %s\n", optarg );
        		break;
        	default:
        		printf("Bad argument value for %s: %s\n", long_options[option_index].name, optarg );
        		break;
        	};
        	break;
        default:
        	printf("?? getopt returned character code 0%o ??\n", c);
        	break;
        };
	}
	dd = open( DEVICE, O_RDONLY );
	if ( dd == -1 ) {
		perror( "Can't open file " DEVICE );
		return -1;
	}

	if (action==STOP) {
		ioctl( dd, MAPMOD_IOCTL_ROTATE_STOP );
	} else if (action==START) {
		ioctl( dd, MAPMOD_IOCTL_ROTATE_START );
	} else if (action==RPM) {
		switch (rpm) {
		case 2:
			ioctl( dd, MAPMOD_IOCTL_SET_RPM2 );
			break;
		case 4:
			ioctl( dd, MAPMOD_IOCTL_SET_RPM4 );
			break;
		case 6:
			ioctl( dd, MAPMOD_IOCTL_SET_RPM6 );
			break;
		case 12:
			ioctl( dd, MAPMOD_IOCTL_SET_RPM12 );
			break;
		default:
			break;
		};
	}

	close( dd );
	return 0;
}
